//
//  SCImageUploadManager.m
//  Shuaiche
//
//  Created by dangshuai on 2019/4/26.
//  Copyright © 2019 zzs. All rights reserved.
//

#import "SCImageUploadManager.h"
#import <AliyunOSSiOS/OSSService.h>
#import <AliyunOSSiOS/OSSCompat.h>
#import "SCHttpManager.h"
#import "MBProgressHUD+Add.h"
#import "NSString+Helper.h"
#import <Photos/Photos.h>
#import "SCNetworkStatusConst.h"

static NSString *const endPoint = @"https://oss-cn-hangzhou.aliyuncs.com";
static NSString *const bucketName = @"imgrep";
static NSString *const kAccessKeyId = @"accessKeyId";
static NSString *const kAccessKeySecret = @"accessKeySecret";
static NSString *const kSecurityToken = @"securityToken";
static NSString *const kExpiration = @"expiration";

@interface SCImageUploadManager ()
@property (strong, nonatomic) dispatch_group_t uploadImageGroup;
@end

@implementation SCImageUploadManager
+ (instancetype)sharedInstance {
    static SCImageUploadManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SCImageUploadManager alloc] init];
        manager.uploadImageGroup = dispatch_group_create();
    });
    return manager;
}
#pragma -mark- 上传图片
+ (void)startUploadImages:(NSArray <SCCarAddImageItemModel *>*)imageArray completion:(void(^)(NSArray *picUrls,NSString *errorString))block {
    
    NSString *datePath = [self datePath];
//    NSMutableArray *imageUrls = [NSMutableArray arrayWithCapacity:0];
    NSMutableArray *imageUrls = [NSMutableArray arrayWithArray:imageArray];
    __block BOOL hasError = NO;

    dispatch_group_t group = [SCImageUploadManager sharedInstance].uploadImageGroup;
    
    //获取所有未上传 图片的localID
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0];
    NSMutableArray *cameraArray = [NSMutableArray arrayWithCapacity:0];
    for (int i = 0; i < imageArray.count; i++) {
        SCCarAddImageItemModel *model = imageArray[i];
        model.positionIndex = [NSIndexPath indexPathForRow:i inSection:0];
       if (model.imageUrlPath) { //已上传过的图片
            NSString *prefix = @"http://img.shuaiche.com";
            NSString *prefixs = @"https://img.shuaiche.com";
            if([model.imageUrlPath hasPrefix:prefix] ||
               [model.imageUrlPath hasPrefix:prefixs]){
                [imageUrls replaceObjectAtIndex:i withObject:[model.imageUrlPath substringFromIndex:prefix.length]];
            } else {
                [imageUrls replaceObjectAtIndex:i withObject:model.imageUrlPath];
            }
            [imageUrls replaceObjectAtIndex:i withObject:model.imageUrlPath];
        }else if (model.asset) {
            [dic setValue:model.positionIndex forKey:model.asset.localIdentifier];
        }else {
            [cameraArray addObject:model];
        }
    }

    //筛选相同图片数组
     NSMutableArray *groupArray = [NSMutableArray arrayWithCapacity:0];
     for (NSString *ID in dic.allKeys) {
         NSPredicate *predicate = [NSPredicate predicateWithFormat:@"asset.localIdentifier contains %@", ID];
         NSArray<SCCarAddImageItemModel *> *array = [imageArray filteredArrayUsingPredicate:predicate];
         array.firstObject.isSameFirst = YES;
         [groupArray addObject:array];
     }
    if (cameraArray.count) {
        [groupArray addObject:cameraArray];
    }
    [[SCHttpManager shareInstance] httpGet:@"https://api.shuaiche.com/baseprod/resource/access" param:nil completion:^(NSDictionary *responseJson, NSError *error) {
    if (error) {
        if (block) {
            block(nil,error.localizedDescription);
        }
    } else {
        id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
            OSSFederationToken * token = [OSSFederationToken new];
            token.tAccessKey = responseJson[kAccessKeyId];
            token.tSecretKey = responseJson[kAccessKeySecret];
            token.tToken = responseJson[kSecurityToken];
            token.expirationTimeInGMTFormat = responseJson[kExpiration];
            return token;
        }];
        OSSClient *client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
        [groupArray enumerateObjectsUsingBlock:^(NSArray<SCCarAddImageItemModel *> * _Nonnull array, NSUInteger idx, BOOL * _Nonnull stop) {
            for (SCCarAddImageItemModel *model in array) {
                dispatch_group_enter(group);
                if (model.isSameFirst || !model.asset) {  //拍照上传的图片 asset为nil
                  NSString *name = [[[NSString UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""] stringByAppendingString:@".jpeg"];;
                    model.name = name;
                    NSString *key = [NSString stringWithFormat:@"%@/%@",datePath,name];
                    OSSPutObjectRequest * putRequest = [OSSPutObjectRequest new];
                    putRequest.objectKey = key;
                    [imageUrls replaceObjectAtIndex:model.positionIndex.row withObject:[NSString stringWithFormat:@"/%@",key]];
                    model.imageUrlPath = [NSString stringWithFormat:@"/%@",key];
                    UIImage *image = model.image;
                    putRequest.uploadingData = UIImageJPEGRepresentation(image, 0.7);
                    putRequest.bucketName = bucketName;
                    putRequest.cacheControl = @"max-age=31104000";
                    OSSTask * task = [client putObject:putRequest];
                    NSLog(@"打印次数  总张数%lu",(unsigned long)imageArray.count);
                    [task continueWithBlock:^id(OSSTask *task) {
                        if (task.error) {
                            NSLog(@"Put image failed, %@", task.error);
                            model.imageUrlPath = nil;
                            *stop = YES;
                            hasError = YES;
                        } else {
                            NSLog(@"Put image success!");
                        }
                        dispatch_group_leave(group);
                        return nil;
                    }];
                  // 等待任务完成。
                   [task waitUntilFinished];
                }else {
                    model.name = array.firstObject.name;
                    [imageUrls replaceObjectAtIndex:model.positionIndex.row withObject:array.firstObject.imageUrlPath];
                    dispatch_group_leave(group);
                }
            }
        }];
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                if (block) {
                    if (hasError) {
                        block(nil,@"网络请求超时,请重新尝试!");
                    } else {
                        block(imageUrls,nil);
                    }
                }
            });
        }
    }];
}

+ (void)uploadingWithFileData:(NSData *)fileData filePath:(NSString *)filePath uploadType:(NSUInteger)uploadType completion:(void(^)(NSString *filePath))block{
  [[SCHttpManager shareInstance] httpGet:@"https://api.shuaiche.com/baseprod/resource/access" param:nil completion:^(NSDictionary *response, NSError *error) {
    if(!error){
        OSSClient *client = [SCImageUploadManager
                             ossInitWithAccessKey:response[kAccessKeyId] secretKey:response[kAccessKeySecret] securityToken:response[kSecurityToken] expirationTimeInGMTFormat:response[kExpiration]];
        NSString *fileName = [filePath lastPathComponent];
        NSString *key = [NSString stringWithFormat:@"%@/%@",[SCImageUploadManager pdfFilePath:uploadType],fileName];
        OSSPutObjectRequest * putRequest = [OSSPutObjectRequest new];
        putRequest.objectKey = key;
        putRequest.uploadingData = fileData;
        putRequest.bucketName = bucketName;
        putRequest.cacheControl = @"max-age=31104000";

        OSSTask * task = [client putObject:putRequest];
        [task continueWithBlock:^id(OSSTask *task) {
            //OSSPutObjectResult * result = task.result;
            dispatch_async(dispatch_get_main_queue(), ^{
                if (!task.error) {
                    NSLog(@"Put image success!");
                    block(key);
                } else {
                    NSLog(@"Put image failed, %@", task.error);
                    block(nil);
                }
            });
            return nil;
        }];
       // 等待任务完成。
       [task waitUntilFinished];
    }else{
        block(nil);
      [MBProgressHUD showError:error.localizedDescription toView:nil];
    }
}];
}

+ (OSSClient *)ossInitWithAccessKey:(NSString *)accessKey secretKey:(NSString *)secretKey securityToken:(NSString *)securityToken expirationTimeInGMTFormat:(NSString *)expiration{
    id<OSSCredentialProvider> credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
        OSSFederationToken * token = [OSSFederationToken new];
        token.tAccessKey = accessKey;
        token.tSecretKey = secretKey;
        token.tToken = securityToken;
        token.expirationTimeInGMTFormat = expiration;
        return token;
    }];
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:endPoint credentialProvider:credential];
    return client;
}

+ (NSString *)getMediaNameWithPHAsset:(PHAsset *)asset {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *mediaName;
    //空的情况，返回自定义名称（按时间命名）
    if (!asset) {
        mediaName = [formatter stringFromDate:date];
        return [NSString stringWithFormat:@"%@Image.png",mediaName];
    }
    PHAssetResource *resource = [[PHAssetResource assetResourcesForAsset:asset] firstObject];
    //获取本地原图的名称
    if (resource.originalFilename) {
        mediaName = resource.originalFilename;
    }else {
        mediaName = [NSString stringWithFormat:@"%@Image.png",[formatter stringFromDate:date]];
    }
    return mediaName;
}

+ (NSString *)datePath{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMM"];
    NSString *datePath = [dateFormatter stringFromDate:date];
    
#ifdef APP_STORE
    return [NSString stringWithFormat:@"img/%@",datePath];
#else
    return [NSString stringWithFormat:@"temp/%@",datePath];
#endif
}

+ (NSString *)pdfFilePath:(NSUInteger)uploadType{
    
#ifdef APP_STORE
    if (uploadType == 0) {//维保
        return [NSString stringWithFormat:@"file/car/maintainreport"];
    }else{
        return [NSString stringWithFormat:@"file/car/testreport"];
    }
#else
    if (uploadType == 0) {
        return [NSString stringWithFormat:@"temp/file/car/maintainreport"];
    }else{
        return [NSString stringWithFormat:@"temp/file/car/testreport"];
    }
#endif
    
}

@end
